// pages/tobuy/tobuy.js
// import { ColorGradient } from 'XrFrame/components/particle/gradient'
import {
  getMyAddress,
  addCommomAddress,
  changeOrderGoods,
  createOrder
} from '../../apis/api'
import WxValidate from '../../utils/WxValidate'
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date:'请输入配送时间',
    orderList: [],
    allGoodsNum: 0,
    addressList: [],
    showModalStatus: false,
    showModalChangeStatus: false,
    customItem: '全部',
    checkedId: 0,
    city: false,
    region: ['', '', ''],
    card_id: 0,
    addressDTO: {
      addressRemark: '崇明味道太好吃啦',
      address: '',
      area: 'in',
      city: 'the',
      telephone: '',
      receiver: '',
      universalEnum: 'SAVE_UPDATE'
    },
    inventors: [],
    submitType: '',
    remark: '',
    single:'',
    form:{},
    isUpdate:true,
    type:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.showModal({
      title: '提示',
      content: "默认配送时间为"+util.GetDateStr(1)+"，下单时间晚于15:00，会在隔天发货，您可以选择修改默认配送时间"
      
    })
    this.setData({
      date:util.GetDateStr(1)
    })
    if (options) {
      console.log(options)
      if(options.form!=null){
        this.setData({
          form:JSON.parse(options.form),
          orderList:JSON.parse(options.form).inventors,
          isUpdate:false
        })
      }else{
        this.setData({
          orderList: JSON.parse(options.list),
          card_id: parseInt(options.card),
          submitType: options.cardtype,
          type:options.type,
          single:options.single,
          isUpdate:true
        })
      }
      // if(this.data.submitType){

      // }
     
    }
    this.getAllGoodsNum()
    this.getGoodsToSubmit()
    await this.getMyAddress()
    this.initValidate()
    this.setData({
      checkedId: parseInt(this.data.addressList[0].id)
    })
  },
  closeView(){
    this.setData({
      showModalStatus:false
    })
  },
  // 单选
  radioChange(e) {
    this.setData({
      checkedId: e.detail.value
    })
  },
   
  bindDateChange(e){
    let newdate=Date.parse(e.detail.value)
    let todate=Date.parse(util.GetDateStr(1))
    if(todate>newdate){
      wx.showToast({
        title: '时间不正确',
        icon: 'error',
        duration: 1000
      })
    }else{
      this.setData({
        date: e.detail.value,
        startDate:util.formatDay(new Date())
      })
    }
   
  },
  // 获取所有要下单的商品
  getAllGoodsNum: function () {
    let sum = 0
    for (let i = 0; i < this.data.orderList.length; i++) {
      sum += this.data.orderList[i].buyNum
    }
    this.setData({
      allGoodsNum: sum
    })
  },
  // 获取全部地址 
  getMyAddress: async function () {
    const userId = wx.getStorageSync('userId')
    const res = await getMyAddress({
      userId,
      isDelete: 0
    })
    let list=[]
    let isFlag=false
    if(res&&res.code===200){
      res.data.forEach(item=>{
        console.log(item)
         isFlag=false
       for(let i=0 ;i<list.length;i++){
         if(item.address==list[i].address){
          isFlag=true
           break
         }
       }
       if(!isFlag){
        list.push(item)
       }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: res.messages,
      })
    }
    this.setData({

      addressList: list
    })
  },
  // 省市区切换
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      city: true
    })
  },

  // 获取需要提交的商品信息
  getGoodsToSubmit: function () {
    const list = [...this.data.orderList]
    for (let i = 0; i < list.length; i++) {
      list[i].dishesMainId = list[i].dishId
      list[i].quantity = list[i].buyNum
      list[i].dishesMainName = list[i].dishName
    }
    this.setData({
      inventors: list
    })
  },
  // 获取备注
  remarkInputAction(e) {
    this.setData({
      remark: e.detail.value
    })
    console.log(this.data.remark);
  },
  // 提交订单
  nextBuy: async function (e) {
    const submitForm = {
      cardId: this.data.card_id,
      addressId: this.data.checkedId,
      inventors: this.data.inventors,
      cardAccount: this.data.submitType,
      remark: this.data.remark,
      deliverTime:this.data.date,
      single:this.data.single
    }
    console.log(submitForm)
    const res = await createOrder(submitForm)
    if (res.code !== 200) {
      return wx.showModal({
        title: '提示',
        content:  res.msg,
      })
    }
    wx.setStorageSync('vegetableList', [])
    wx.setStorageSync('meetList', [])
    wx.setStorageSync('eggList', [])
    wx.setStorageSync('riceList', [])
    wx.setStorageSync('fishList', [])
    wx.setStorageSync('bestList', [])
    wx.setStorageSync('cornList', [])
    wx.setStorageSync('fruitList', [])
    wx.setStorageSync('birdList', [])
    wx.setStorageSync('meetliveList', [])
    wx.showToast({
      title: '下单成功',
      icon: 'success',
      duration: 1000
    })
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/order/order',
      })
    }, 1000)
  },
  
  // 修改订单
  updateBuy: async function(){
    var _this=this.data
     wx.showModal({
      title: '提示',
      content: '所有订单可修改且仅可修改一次，是否继续？',
      success: function (res) {
      
        if (res.confirm) {
          console.log(_this)
          const submitForm = {
            addressId: _this.form.addressId,
            remark: _this.remark,
            deliverTime:_this.date,
          }
          console.log({...submitForm,..._this.form})
          changeOrderGoods({...submitForm,..._this.form}).then(res => {
    // const res = await changeOrderGoods({...submitForm,..._this.form})
    console.log(res)
    if (res.code !== 200) {
          return wx.showToast({
            title: '修改订单失败',
            icon: 'error',
            duration: 2000
          })
        }
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/order/order',
          })
        }, 1000)
        wx.showToast({
          title: '修改订单成功',
          icon: 'success',
          duration: 1000
        })
      })
    }
  }
})
    
  },
  
  // 新增地址弹窗
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
    this.utilChange('close')
  },
  // 新增地址
  powerDrawerClick: async function (e) {
    // var currentStatu = e.currentTarget.dataset.statu;
    // await addCommomAddress(this.data.addressDTO)
    // const newAddressList = [...this.data.addressList]
    // newAddressList.unshift(this.data.addressDTO)
    // const ress = await getMyAddress()
    // this.setData({
    //   addressList: newAddressList,
    //   checkedId: ress.data[ress.data.length-1].id
    // })
    // this.util(currentStatu)
  },
  util: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 200, 
      timingFunction: "linear", 
      delay: 0  
    });
    this.animation = animation;
    animation.opacity(0).rotateX(-100).step(); 
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationData: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  // 修改地址弹窗
  powerDrawerChange: async function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.utilChange(currentStatu)
  },
  // 修改地址
  powerDrawerChangeClick: async function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    console.log(this.data.checkedId)
    const index = this.data.addressList.findIndex(item => {
      return item.id === parseInt(this.data.checkedId)
    })
    const thatAddress = this.data.addressList[index]
    const newAddressList = [...this.data.addressList]
    newAddressList.splice(index, 1)
    newAddressList.unshift(thatAddress)
    this.setData({
      addressList: newAddressList
    })
    this.utilChange(currentStatu)
  },
  utilChange: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });
    this.animation = animation; 
    animation.opacity(0).rotateX(-100).step();
    this.setData({
      animationDataChange: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationDataChange: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalChangeStatus: false
        });
      }
    }.bind(this), 200) 
    if (currentStatu == "open") {
      this.setData({
        showModalChangeStatus: true
      });
    }
  },
  // 新增数据绑定
  bindUsernameChange: function (e) {
    this.setData({
      ['addressDTO.receiver']: e.detail.value
    })
  },
  bindTelephoneChange: function (e) {
    this.setData({
      ['addressDTO.telephone']: e.detail.value
    })
  },
  bindAddressChange: function (e) {
    const address = this.data.region.join('');
    this.setData({
      ['addressDTO.address']: address + e.detail.value
    })
  },
  // 校验
  showModal(err) {
    wx.showModal({
      content: err.msg,
      showCancel: false
    })
  },
  initValidate() {
    const rules = {
      aNickname: {
        required: true
      },
      aTelephone: {
        required: true,
        tel: true
      },
      aRegionone: {
        required: true
      },
      aRegiontwo: {
        required: true
      },
      aRegionthree: {
        required: true
      },
      aAddress: {
        required: true
      }
    }
    const messages = {
      aTelephone: {
        required: '请输入手机号',
        tel: '请输入正确的手机号'
      },
      aNickname: {
        required: '请输入收货人'
      },
      aRegionone: {
        required: '请选择省份'
      },
      aRegiontwo: {
        required: '请选择省份'
      },
      aRegionthree: {
        required: '请选择省份'
      },
      aAddress: {
        required: '请输入地址'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  formSubmit: async function (e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    var currentStatu = e.detail.target.dataset.statu;
    await addCommomAddress(this.data.addressDTO)
    const newAddressList = [...this.data.addressList]
    newAddressList.unshift(this.data.addressDTO)
    const userId = wx.getStorageSync('userId')
    const ress = await getMyAddress({
      userId,
      isDelete: 0
    }
    )
    this.setData({
      addressList: newAddressList,
      checkedId: ress.data[ress.data.length-1].id
    })
    this.util(currentStatu)
  },
})